package cn.tedu.egarticle1.controller;

import cn.tedu.egarticle1.base.reponse.JsonResult;
import cn.tedu.egarticle1.base.reponse.StateCode;
import cn.tedu.egarticle1.mapper.ArticleMapper;
import cn.tedu.egarticle1.mapper.UserMapper;
import cn.tedu.egarticle1.pojo.dto.ArticleParam;
import cn.tedu.egarticle1.pojo.dto.UserLoginParam;
import cn.tedu.egarticle1.pojo.entity.Article;
import cn.tedu.egarticle1.pojo.vo.ArticleVO;
import cn.tedu.egarticle1.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpSession;
import java.util.List;

@Validated
@Slf4j
@Api(tags = "01.用户管理")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    //登录功能
    @PostMapping("login")
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam:"+userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserVO userVO = (UserVO) userMapper.selectByUsernameAndPassword(username,password);
        if (userVO != null){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StateCode.USERNAME_PASSWORD_ERROR);
    }
    //发表文章
    @ApiOperation("发表文章")
    @ApiOperationSupport(order = 20)
    @PostMapping("article")
    public JsonResult UserArticle(@RequestBody  @Validated ArticleParam articleParam ,@ApiIgnore HttpSession session){
        log.debug("articleParam:"+articleParam);
        UserVO userVO  = (UserVO)session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(articleParam,article);
        article.setUserId(userVO.getId());
        articleMapper.insert(article);
        return JsonResult.ok();
    }
    //查询指定文章
    @ApiOperation("查询指定文章功能")
    @ApiOperationSupport(order = 30)
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章ID要求在1-100之间") @RequestParam String id){
        List<ArticleVO> articleVO = articleMapper.selectArticleById(id);
        return JsonResult.ok(articleVO);
    }
}





















